package com.jhy.product.exception;

import com.jhy.common.exception.BizCodeEnum;
import com.jhy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: controller统一的异常处理类
 *
 * @ControllerAdvice--->用来处理全局异常
 * @author: jhy
 * @time: 2021/5/17 9:11
 */
@Slf4j
@ControllerAdvice(basePackages = "com.jhy.product.controller")
@ResponseBody
public class ExceptionControllerAdvice {

    //用来处理参数校验未通过的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handelValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();

        //将错误封装到Map中，返回给前端
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            //获得发生错误的字段
            String field = item.getField();
            //获得发生错误的message
            String message = item.getDefaultMessage();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),
                BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);

    }

    //默认的异常处理--->精确匹配不到的异常
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        log.error("异常描述{}，异常类型{}",throwable.getMessage(),throwable.getClass());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),
                BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
